package com.zhiwei.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zhiwei.common.constant.ErrorEnum;
import com.zhiwei.common.constant.HttpConstants;
import com.zhiwei.common.constant.ResultResponseMsg;
import com.zhiwei.gateway.dao.entity.AuthorityInfo;
import com.zhiwei.gateway.dao.entity.UserInfo;
import com.zhiwei.gateway.service.UserTokenService;
import com.zhiwei.gateway.service.WhiteListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * JWT Token过滤器
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private WhiteListService whiteListService;
    @Autowired
    private PathMatcher pathMatcher;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String jwtToken = request.getHeader(HttpConstants.HEADER_TOKEN);
        if (!checkWhiteList(request.getRequestURI()) && !StringUtils.isEmpty(jwtToken)) {
            UserInfo userInfo = userTokenService.getUserInfoByToken(jwtToken);
            if (null != userInfo) {
                List<AuthorityInfo> authorityInfoList = userTokenService.queryAuthorityByToken(jwtToken);
                UsernamePasswordAuthenticationToken authentication = null;
                if (!CollectionUtils.isEmpty(authorityInfoList)) {
                    authentication = new UsernamePasswordAuthenticationToken(userInfo.getUsername(),
                            userInfo.getEmail(), Collections.emptyList());
                } else {
                    List<String> authorities = authorityInfoList.stream().map(AuthorityInfo::getEname).collect(Collectors.toList());
                    authentication = new UsernamePasswordAuthenticationToken(userInfo.getUsername(),
                            userInfo.getEmail(), AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.collectionToCommaDelimitedString(authorities)));
                }
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }else{
                log.error("请求路径【{}:{}】Token校验失败，请使用正确Token访问", request.getRequestURI(), jwtToken);
                ResultResponseMsg resultResponseMsg = ResultResponseMsg.buildResultMsg(ErrorEnum.HTTP_TOKEN, null);
                response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                response.getWriter().println(JSON.toJSONString(resultResponseMsg, SerializerFeature.WriteMapNullValue));
                response.getWriter().flush();
                response.getWriter().close();
                return;
            }
        }
        chain.doFilter(request, response);
    }

    private boolean checkWhiteList(String requestUri) {
        List<String> whiteList = whiteListService.queryValidWhiteList();
        for (String path : whiteList) {
            if (pathMatcher.match(path, requestUri)) {
                return true;
            }
        }
        return false;
    }
}